﻿using System.Security.Claims;
using Microsoft.AspNetCore.Http.Extensions;

namespace Cngot.Extensions.Logger
{
    public class UserEnricher : ILogEventEnricher
    {
        private readonly IHttpContextAccessor _contextAccessor;

        public UserEnricher() : this(new HttpContextAccessor())
        {
        }

        internal UserEnricher(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }

        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var context = _contextAccessor.HttpContext;
            if (context == null || context.Connection == null || context.Request == null)
            {
                return;
            }

            if (context?.User != null && context.User.Identity.IsAuthenticated)
            {
                var userId = context.User.FindFirstValue("sub");
                if (!string.IsNullOrEmpty(userId))
                {
                    logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserId", userId));
                }
                var userName = context.User.Identity?.Name;
                if (!string.IsNullOrEmpty(userName))
                {
                    logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserName", userName));
                }
            }
            else
            {
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("TenantId", ""));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserId", ""));
            }
        }
    }
}
